import { wxLogin as ToLogin, getUserInfo, register } from '@/network/api'
import logo from '@/static/images/logo.jpg'
const auth = {
  state: {
    token: '',
    userInfo: {},
  },
  getters: {
    isVip(state) {
      const nowTime = new Date().getTime() / 1000
      return nowTime < state.userInfo.vipExpireTime
    },
    avatar(state) {
      return state.userInfo.avator_url || logo
    },
  },
  mutations: {
    setToken(state, token) {
      uni.setStorageSync('token', token)
      state.token = token
    },
    setUserInfo(state, userInfo) {
      uni.setStorageSync('userInfo', userInfo)
      state.userInfo = userInfo
    },
    logout(state) {
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      state.token = ''
      state.userInfo = {}
    },
  },
  actions: {
    async wxLogin({ commit, dispatch }, data) {
      try {
        const res = await ToLogin(data)
        commit('setToken', res.token)
        await dispatch('getUserInfo')
      } catch (e) {
        console.log('返回错误', e)
        // uni.redirectTo({
        //   url: '/pages/login/index',
        // })
        //TODO handle the exception
      }
    },
    async getUserInfo({ commit }, data) {
      try {
        const res = await getUserInfo(data)
        commit('setUserInfo', res.info)
      } catch (error) {
        uni.showToast({
          title: 'error',
          message: error.message,
        })
      }
    },
    async Iregister({ commit }) {
      await register({
        Phone: '13247022110',
      })
    },
  },
}
export default auth
